// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class monsterMediator extends cc.Component {

    @property()
    index : number = 1;

    followNode : cc.Node = null;

    openCheck = true;

    moveSpeed = 1.5;

    finalNode = false;

    onLoad(){
        this.followNode = cc.find("Canvas/role");
        cc.game.on("openFollow",(target,res?)=>{
            this.followNode = target;
            if(res){
                this.moveSpeed = res;
                this.finalNode = true;
            }
        })
    }

    protected onDestroy(): void {
        cc.game.off("openFollow");
    }

    update (dt) {
        if(!this.openCheck) return;
        let pos;
        pos = this.followNode.convertToWorldSpaceAR(cc.v2(0,0));
        let pos2 = cc.find("Canvas").convertToNodeSpaceAR(pos);
        let myPos = cc.v2(this.node.x,this.node.y);
        let pos3 = pos2.sub(myPos).normalize();
        let distance = pos2.sub(myPos).mag();
        if(distance >= 5 && Math.abs(this.followNode.y) <= 375){
            this.node.x += pos3.x * this.moveSpeed;
            this.node.y += pos3.y * this.moveSpeed;
        }else{
            if(this.finalNode){
                this.openCheck = false;
                this.node.parent = this.followNode.parent;
                this.node.position = this.followNode.parent.getChildByName("point" + this.index).position;
            }
        }
    }
}
